/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Action;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author 52166986
 */
public class RegistrationServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (!"Registration".equals(request.getParameter("action"))) {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                /*
                 * TODO output your page here. You may use following sample
                 * code.
                 */
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Registration Page</title>");                
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Registration</h1>");
                out.println("<form action='Registration' method='POST'>");
                out.println("<input type='hidden' name='action' value='Registration'/>");
                out.println("  <p>User name: <input type='text' name='j_username'/></p>");
                out.println("  <p>Password: <input type='password' name='j_password'/></p>");
                out.println("  <p>Confirm Password: <input type='password' name='j_password2'/></p>");
                out.println("  <p>Email: <input type='text' name='j_email'/></p>");
                out.println("  <p><input type='submit' value='Register' /></p>");
                out.println("</form>");
                out.println("</body>");
                out.println("</html>");
            } finally {                
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
        doAction(request,response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
        private void doAction(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        if (request.getParameter("action") != null &&
                "Registration".equals(request.getParameter("action"))) {
            String username = (String) request.getParameter("j_username");
            String email = (String) request.getParameter("j_email");
            String password = (String) request.getParameter("j_password");
            double newUID = Math.floor(Math.random()*100);
            //String UID = newUID.toString();
            //UID =  newUID.PadLeft(6, '0');
            //System.out.println(UID);
            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                Connection con = DriverManager.getConnection("jdbc:sqlserver://w2ksa.cs.cityu.edu.hk:1433;databaseName=aiad048_db", "aiad048", "aiad048"); 
                String query = "INSERT INTO [Customers] ([UID], [userName], [email]) VALUES ( ?, ?, ?)";
                String query2 = "INSERT INTO [Login]  ([UID], [password]) VALUES ( ?, ?)";
                PreparedStatement pstmt = con.prepareStatement(query); 
                PreparedStatement pstmt2 = con.prepareStatement(query2); 
                pstmt.setString(1, "000004");
                pstmt.setString(2, email);
                pstmt.setString(3, username);
                pstmt2.setString(1, "000004");
                pstmt2.setString(2, password);
                int rs = pstmt.executeUpdate();
                int rs2 = pstmt2.executeUpdate();
                
                if (rs > 0 && rs2 > 0) {
                    response.sendRedirect("Login");
                }else {
                    response.setHeader("Refresh","0:URL=Registration");
                }
            } catch(IllegalStateException ex){
                 Logger.getLogger(RecoveryServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(RecoveryServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(RecoveryServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
    }
}
